import { Info } from '@/appUtils/appData/lanhuTypes'
import { downloadImg } from '@/appUtils/downloadImg'
import { stats } from '@/appUtils/fs'
import { basename } from '@/appUtils/path'
import { MessageBoxReplace } from '@/components/MessageBoxReplace'
import { mouse } from '@/utils/keyboardAndMouse'
import { ElMessage } from 'element-plus'
import { toRaw } from 'vue'

// 把上一次的targetPath缓存下来，例如在键盘发生变化时，事件中拿不到targetPath
// 这时可以使用上一次的targetPath

/** 根据fileList，target，键盘按键更新鼠标文本 */
export const updateMouseTextForSliceInfo = async (sliceInfo?: Info, targetPath?: string) => {
    if (!sliceInfo && !targetPath) {
        mouse.setText('')
        return
    }
    if (sliceInfo) {
        mouse.setText(`${sliceInfo.name}`)
    }
    if (!sliceInfo || !targetPath) {
        return
    }
    let str = `${sliceInfo.name}`
    const stat = await stats(targetPath)
    if (stat.isDir) {
        str = '复制'
        str += ` ${sliceInfo.name} 到 ${basename(targetPath)}`
    } else {
        str = `替换${basename(targetPath)}`
    }
    mouse.setText(str)
}

/** 放开鼠标，拖放时 */
const handleDrop = async (sliceInfo?: Info, targetPath?: string) => {
    targetPath = targetPath
    if (!sliceInfo || !targetPath) {
        return
    }
    const stat = await stats(targetPath)

    const image = toRaw(sliceInfo.image!)
    if (!sliceInfo.naturalWidth || !sliceInfo.naturalHeight) {
        ElMessage.error('图片尺寸获取失败')
        return
    }

    const size = {
        width: sliceInfo.naturalWidth,
        height: sliceInfo.naturalHeight
    }

    // 目标是文件夹
    if (stat.isDir) {
        await downloadImg({
            url: image!.imageUrl!,
            targetSize: size,
            targetPath,
            originalFileName: sliceInfo.name
        })
    } else {
        const confirm = await MessageBoxReplace(sliceInfo, targetPath)
        // console.log(confirm, fileList[0].path, targetPath)
        if (confirm) {
            try {
                await downloadImg({
                    url: image!.imageUrl!,
                    targetSize: size,
                    targetPath,
                    originalFileName: sliceInfo.name
                })
                ElMessage.success('下载成功')
            } catch (e) {
                console.log(e)
                ElMessage.error('下载失败')
            }
        }
    }
}

export const handleDropEnterForInfo = async (data: Info, targetPath: string) => {
    const info = data
    if (!info || !targetPath) return
    updateMouseTextForSliceInfo(info, targetPath)
}

export const handleDropForInfo = async (data: Info, targetPath: string) => {
    const info = data
    if (!info || !targetPath) return
    await handleDrop(info, targetPath)
}
